/**********************************************
 * 
 * File Name				:	CommonActionImpl.java
 * 
 * Last Changed Date		: 	$Date: 2009-08-06 14:51:00 +0800 (星期四, 06 八月 2009) $
 * 
 * Last Changed Revision	:	$Revision: 92 $
 * 
 * Last Changed Author		:	$Author: cfanboy $
 * 
 * File Header URL			:	$HeadURL: svn://www.svnhost.cn/Busi-Building/code/branch/src/com/busibuilding/common/action/CommonActionImpl.java $
 * 
 * ********************************************
 */

package com.busibuilding.common.action;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.web.util.HtmlUtils;
import org.springframework.web.util.WebUtils;

import com.busibuilding.administrate.security.vo.UserCVO;
import com.busibuilding.common.Constants;
import com.busibuilding.common.vo.ICommonVO;
import com.busibuilding.utils.DateUtils;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

/**
 * Class Name: CommonActionImpl.java 
 * Description: This common action
 * @author: YU Zhipeng
 * @version: 1.0
 * @since: 1.0
 * Date: 2009-07-09
 */

@SuppressWarnings("unchecked")
public abstract class CommonActionImpl extends ActionSupport implements Constants,
		Preparable, SessionAware, ParameterAware, RequestAware {
	
	private static final long serialVersionUID = -4586299007851178246L;
	
	private static Logger logger = Logger.getLogger(CommonActionImpl.class);
	
	/**
	 * Map of session attributes
	 */
	protected Map sessionMap;
	/**
	 * Map of input parameters 
	 */
	protected Map paramMap;
	/**
	 * Map of request attributers
	 */
	protected Map requestMap;
	/**
	 * HttpServletRequest Object
	 */
	protected HttpServletRequest request;
	/**
	 * HttpServletResponse Object
	 */
	protected HttpServletResponse response;
	
	/**
	 * Current page of displaytag
	 */
	protected int currentPage;
	
	protected String menuBar;
	
	
	public String getMenuBar() {
		return menuBar;
	}

	public void setMenuBar(String menuBar) {
		this.menuBar = menuBar;
	}

	/**
	 * Common result string
	 */
	public static final String BACK = "back";
	public static final String INPUT = "input";
	public static final String SEARCH = "search";
	public static final String RESET = "reset";
	public static final String CREATE = "create";
	public static final String UPDATE = "update";
	public static final String DELETE = "delete";
	
	
	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	/**
	 * Return the HttpServletRequest object
	 * @return HttpServletRequest
	 */
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	/**
	 * Return the HttpServletResponse object
	 * @return HttpServletResponse
	 */
	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	/**
	 * Return the HttpSession object
	 * @return
	 */
	protected HttpSession getSession() {
		return getRequest().getSession();
	}
	
	/**
	 * Return the attribute value from session via passed key
	 * @param key
	 * @return Object
	 */
	protected Object getSessionAttribute(String key){
		return WebUtils.getSessionAttribute(getRequest(), key);
	}
	
	/**
	 * Return session id
	 * @return String
	 */
	protected String getSessionId(){
		return WebUtils.getSessionId(getRequest());
	}
	
	/**
	 * Return the cookie via passed cookie name
	 * @param cookieName
	 * @return
	 */
	protected Cookie getCookie(String cookieName){
		return WebUtils.getCookie(getRequest(), cookieName);
	}
	
	/**
	 * Set object to session
	 * @param key
	 * @param obj
	 */
	protected void setSessionAttribute(String key, Object obj){
		WebUtils.setSessionAttribute(getRequest(), key, obj);
		
	}
	
	/**
	 * Escape the html
	 * @param str
	 * @return
	 */
	protected String htmlEscape(String str){
		return HtmlUtils.htmlEscape(str);
	}
	
	/**
	 * Escape the html, the number and special character will be replaced to decimal
	 * @param str
	 * @return
	 */
	protected String htmlEscapeDecimal(String str){
		return HtmlUtils.htmlEscapeDecimal(str);
	}
	
	/**
	 * Escape the html, the number and special character will be replaced to hex
	 * @param str
	 * @return
	 */
	protected String htmlEscapeHex(String str){
		return HtmlUtils.htmlEscapeHex(str);
	}
	
	/**
	 * Unescape the escape html to normal html format.
	 * @param str
	 * @return
	 */
	protected String htmlUnescape(String str){
		return HtmlUtils.htmlUnescape(str);
	}
	@Override
	public void prepare() throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setSession(Map map) {
		this.sessionMap = map;
		
	}

	@Override
	public void setParameters(Map map) {
		this.paramMap = map;
		
	}

	@Override
	public void setRequest(Map map) {
		this.requestMap = map;		
	}
	
	/**
	 * Display the transaction successfully message
	 * @param key <Message key in applicationResources.properties>
	 */
	public void txnSuccessful(String key){
		if (!this.hasErrors()){
			this.addActionMessage(this.getText(key));
		}
	}
	
	/**
	 * Display the transaction failure message
	 * @param key <Message key in applicationResources.properties>
	 */
	public String txnFailure(String key){
		logger.error("ERROR -");
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("BACK", "true");
		this.addActionError(this.getText(key));
		return INPUT;
	}
	
	/**
	 * To complete the administrator information that needed for creating, such as createdBy, updatedDate etc.
	 * @param vo
	 * @return ICommonVO
	 */
	public ICommonVO getAdminCommonInformationForCreate(ICommonVO vo){
		UserCVO admin = (UserCVO)getSessionAttribute(SESSION_LOGON_ADMIN_USER);
		if (admin != null){
			Date date = DateUtils.getCurrentTimestamp();
			vo.setCreatedBy(admin.getUserId());
			vo.setCreatedDate(date);
			vo.setLastUpdatedBy(admin.getUserId());
			vo.setLastUpdatedDate(date);
			vo.setDefunctInd(NO);
			vo.setVersion(INIT_VERSION);
		}
		return admin;
	}
	
	/**
	 * To complete the administrator information that needed for update, only lastUpdatedBy and lastUpdateDate to be set.
	 * @param vo
	 * @return ICommonVO
	 */
	public ICommonVO getAdminCommonInformationForUpdate(ICommonVO vo){
		UserCVO admin = (UserCVO)getSessionAttribute(SESSION_LOGON_ADMIN_USER);
		if (admin != null){
			vo.setLastUpdatedBy(admin.getUserId());
			vo.setLastUpdatedDate(DateUtils.getCurrentTimestamp());
		}
		return admin;
	}
	
	/**
	 * To complete the normal user information that needed for creating, such as createdBy, updatedDate etc.
	 * @param vo
	 * @return ICommonVO
	 */
	public ICommonVO getUserCommonInformationForCreate(ICommonVO vo){
		UserCVO user = (UserCVO)getSessionAttribute(SESSION_LOGON_USER);
		if (user != null){
			Date date = DateUtils.getCurrentTimestamp();
			vo.setCreatedBy(user.getUserId());
			vo.setCreatedDate(date);
			vo.setLastUpdatedBy(user.getUserId());
			vo.setLastUpdatedDate(date);
			vo.setDefunctInd(NO);
			vo.setVersion(INIT_VERSION);
		}
		return user;
	}
	
	/**
	 * To complete the normal user information that needed for update, only lastUpdatedBy and lastUpdateDate to be set.
	 * @param vo
	 * @return ICommonVO
	 */
	public ICommonVO getUserCommonInformationForUpdate(ICommonVO vo){
		UserCVO user = (UserCVO)getSessionAttribute(SESSION_LOGON_USER);
		if (user != null){
			vo.setLastUpdatedBy(user.getUserId());
			vo.setLastUpdatedDate(DateUtils.getCurrentTimestamp());
		}
		return user;
	}
	
//	/**
//	 * Retrieve the pagination information for displaytag.
//	 * 	- pageSize 	: the size of per page
//	 * 	- page		: the current page number
//	 * 	- fromIndex	: the record that will be got start index.
//	 * 	- toIndex	: the record that will be got end index.
//	 * @return
//	 */
//	protected int[] getCurrentPageParameter() {
//		int pageSize = DEFAULT_PAGE_SIZE;
//        if (getRequest().getParameter("pagesize") != null && !"".equals(getRequest().getParameter("pagesize"))) {
//        	pageSize = Integer.parseInt(getRequest().getParameter("pagesize"));
//        }
//        
//		int page = DEFAULT_PAGE;
//        if (getRequest().getParameter(TableTagParameters.SORT_AMOUNT_PAGE) != null && !"".equals(getRequest().getParameter(TableTagParameters.SORT_AMOUNT_PAGE))) {
//        	page = Integer.parseInt(getRequest().getParameter(TableTagParameters.SORT_AMOUNT_PAGE));
//        }
//        
//        setCurrentPage(page);
//        
//        int fromIndex = (page - 1) * pageSize;
//        int toIndex = pageSize;
//        
//		return new int[]{fromIndex, toIndex};
//	}
//
//	/**
//	 * Pagination the page
//	 * @param resultList
//	 * @param listSize
//	 */
//	protected void paging(List<MenuCVO> resultList, int listSize, String displaytagName) {
//		PaginatedListHelper paginaredList = new PaginatedListHelper();
//        ((PaginatedListHelper) paginaredList).setPageNumber(DEFAULT_PAGE);
//        if (resultList.size() > 0 && listSize != 0) {
//            // 总共有多少数据,他会根据所有数目和每页数目自动统计页数
//            ((PaginatedListHelper) paginaredList).setFullListSize(listSize);
//            ((PaginatedListHelper) paginaredList).setObjectsPerPage(DEFAULT_PAGE_SIZE);
//            ((PaginatedListHelper) paginaredList).setList(resultList);
//            ((PaginatedListHelper) paginaredList).setPageNumber(getCurrentPage());
//        } else {
//            ((PaginatedListHelper) paginaredList).setFullListSize(0);
//            ((PaginatedListHelper) paginaredList).setList(null);
//        }
//	
//		if (resultList.size() > 0) {
//			getRequest().setAttribute("fullListSize", listSize);
//			getRequest().setAttribute(displaytagName, paginaredList);
//		}
//	}
}
